import React from 'react';
import PropTypes from 'prop-types';
import ListEmpty from 'atComponents/ListEmpty';
import ImportProjectModal from 'components/importProjectModal/loadable';
import { Button, Message } from '@teamix/ui';
import utils from 'utils';
import exceed from 'utils/apimap';
import { navigate } from 'utils/router';
import {
  PROJECT_ADMIN_ROLES,
  PROJECT_DEVELOPER_ROLES,
  // PROJECT_VIEW_ROLES,
} from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import docs from 'utils/docs';
import track from 'utils/track';
import intl from '../../../../../../../locale';

const defaultNamespaceId = utils.getUrlSearchParam('namespace_id');

const solutionText = (
  <div>
    解决方案：因网络原因导致的无法连通或导入超时，建议检查代码库地址公网连通性，此外支持使用本地
    <a href={docs('importTool')} target="_blank" rel="noreferrer">
      {intl.get({
        id: 'code-assets.components.importProjectListModal.ImportTool',
        defaultMessage: '导入工具',
      })}
    </a>
    进行导入，或初始化空库后由本地进行推送
  </div>
);

const importErrorType = [
  {
    type: 'NETWORK_ERROR',
    label:
      '原代码库网络/端口无法连通，请检查代码库克隆地址并确认公网可访问\n如何检查自建代码库网络设置',
    causeError: '错误原因：网络不通或导入超时',
    solution: solutionText,
  },
  {
    type: 'NETWORK_CONNECTION_ERROR',
    label: '网络连接异常，请重试或通过本地推送代码库',
    causeError: '错误原因：网络不通或导入超时',
    solution: solutionText,
  },
  {
    type: 'IMPORT_TIMEOUT',
    label: '代码库导入超时',
    causeError: '错误原因：网络不通或导入超时',
    solution: solutionText,
  },
  {
    type: 'USERNAME_OR_TOKEN_INVALID',
    label: '用户名或密码/Token验证无效，请确认后重试',
    causeError: '错误原因：路径不存在或账密错误',
    solution: '解决方案：建议先在本地尝试克隆，以检查库路径、账号以及密码/Token是否正确。',
  },
  {
    type: 'AUTHENTICATION_FAILED',
    label: '权限认证失败，请确认后重试',
    causeError: '错误原因：路径不存在或账密错误',
    solution: '解决方案：建议先在本地尝试克隆，以检查库路径、账号以及密码/Token是否正确。',
  },
  {
    type: 'CODING_SERVICE_IS_UNDER_MAINTENANCE',
    label: 'Coding 提示服务正在维护中，请确认后重试',
    causeError: '错误原因：路径不存在或账密错误',
    solution: '解决方案：建议先在本地尝试克隆，以检查库路径、账号以及密码/Token是否正确。',
  },
  {
    type: 'MANUAL_ABORT',
    label: '代码库导入已被中止',
    causeError: '错误原因：代码库导入已被中止',
    solution: '解决方案：请初始化空库或重新导入。',
  },
  {
    type: 'RESOURCE_EXHAUSTED',
    label: '代码库容量超出限制',
    causeError: '错误原因：代码库容量超出限制',
    solution: '解决方案：请工单申请扩容后再试。',
  },
  {
    type: 'REPO_NOT_FOUND_OR_NON_PERMISSION',
    label: '找不到代码库，请确认是否有权限且代码库存在',
    causeError: '错误原因：路径不存在或账密错误',
    solution: '解决方案：建议先在本地尝试克隆，以检查库路径、账号以及密码/Token是否正确。',
  },
  {
    type: 'REMOTE_RETURN_5XX',
    label: '三方服务异常，请于本地验证三方服务是否正常',
    causeError: '错误原因：三方服务异常',
    solution: '解决方案：建议先在本地尝试克隆，确认三方服务正常后再试。',
  },
  {
    type: 'HOST_RESOLVE_FAILED',
    label: 'host解析失败，请检查克隆地址是否符合规范且通公网',
    causeError: '错误原因：网络不通或导入超时',
    solution: solutionText,
  },
  {
    type: 'INVALID_REPO_CLONE_URL',
    label: '重定向错误，请检查克隆地址、用户名密码是否填写正确',
    causeError: '错误原因：路径不存在或账密错误',
    solution: '解决方案：建议先在本地尝试克隆，以检查库路径、账号以及密码/Token是否正确。',
  },
  {
    type: 'UNKNOW_ERROR',
    label: '未知异常',
    causeError: '错误原因：未知异常',
    solution: '解决方案：请稍后再试或联系平台技术支持获取帮助。',
  },
];

export default class ImportFailPage extends React.Component {
  static propTypes = {
    initEmptyProject: PropTypes.func,
    projectInfo: PropTypes.object,
    getProjectInfo: PropTypes.func,
  };

  static defaultProps = {
    initEmptyProject: () => {},
    projectInfo: {},
    getProjectInfo: () => {},
  };

  state = {
    isUrlImportModalShow: false,
  };

  importFailDescHander = () => {
    const {
      projectInfo: { import_error_type },
    } = this.props;
    // const main = 'UNKNOW_ERROR';
    const value = importErrorType.find((va) => va.type === import_error_type);
    if (value) {
      return (
        <div style={{ width: 320 }}>
          <div>{value?.causeError}</div>
          <div>{value?.solution}</div>
        </div>
      );
    } else {
      return (
        <div style={{ width: 320 }}>
          <div>
            {intl.get({
              id: 'code-assets.projectFiles.containers.importFail.PossibleCausesOfImportFailure',
              defaultMessage: '导入失败可能的原因及解决方案：',
            })}
            <br />
            {intl.get({
              id: 'code-assets.projectFiles.containers.importFail.ThePathDoesNotExist',
              defaultMessage: '1.路径不存在；',
            })}
            <br />
            {intl.get({
              id: 'code-assets.projectFiles.containers.importFail.TheAccountOrPasswordIs',
              defaultMessage: '2.帐号或密码不正确；',
            })}
            <br />
            {intl.get({
              id: 'code-assets.projectFiles.containers.importFail.TheNetworkIsDisconnected',
              defaultMessage: '3.网络不通；',
            })}
            <br />
            {intl.get({
              id: 'code-assets.projectFiles.containers.importFail.ImportTimedOut',
              defaultMessage: '4.导入超时；',
            })}
            <br />
          </div>
          <br />
          <div>
            {intl.get({
              id: 'code-assets.projectFiles.containers.importFail.IfYouAreSureTo',
              defaultMessage:
                '如您确认继续导入，建议先在本地尝试克隆，以检查库路径、帐号及密码是否正确；如因网络原因导致的无法连通或导入超时，建议在初始化空库后，在本地进行推送。',
            })}
          </div>
        </div>
      );
    }
  };

  closeUrlModal = () => {
    this.setState({
      isUrlImportModalShow: false,
    });
  };

  remove = (cb) => {
    const { pathResource } = window.FORCE;
    const formData = {
      name: pathResource.projectInfo.name,
      reason: '导入失败手动删除',
    };
    exceed
      .fetch({
        api: 'project.remove.with_reason',
        params: { id: Number(pathResource.id) },
        data: formData,
      })
      .then((result) => {
        if (result.result === true) {
          Message.success({
            title: intl.get({
              id: 'code-assets.components.deletePathResourceDialog.Deleted',
              defaultMessage: '删除成功',
            }),
          });

          navigate('/');
          // navigate(href, { state: { forceUpdate: true } });
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.components.deletePathResourceDialog.UnableToDelete',
              defaultMessage: '删除失败',
            }),
          });
        }
        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态但是弹窗不关闭
        cb && cb('isFail');
      });
  };

  render() {
    const { isUrlImportModalShow } = this.state;
    const {
      initEmptyProject,
      projectInfo,
      getProjectInfo,
      isInittingImport,
      isRemovingProject,
      setImportStatus,
    } = this.props;
    const { role } = window.FORCE.pathResource;
    const isAdmin = access(PROJECT_ADMIN_ROLES, role);
    const isDeveloper = access(PROJECT_DEVELOPER_ROLES, role);
    // const isViewer = access(PROJECT_VIEW_ROLES, role);
    const btns = [
      isAdmin || isDeveloper ? (
        <Button
          type="primary"
          onClick={() => {
            this.setState({
              isUrlImportModalShow: true,
            });

            track({
              action: 'retry_import',
              page: 'Repo-Importing',
              type: 'import by URL',
              control: '',
            });
          }}
        >
          {intl.get({
            id: 'code-assets.projectFiles.containers.importFail.RetryImport',
            defaultMessage: '重试导入',
          })}
        </Button>
      ) : null,
      isAdmin || isDeveloper ? (
        <Button
          type="normal"
          onClick={() => {
            initEmptyProject();
            track({
              action: 'new_repo',
              page: 'Repo-Importing',
              type: 'import by URL',
              control: '',
            });
          }}
          loading={isInittingImport}
        >
          {intl.get({
            id: 'code-assets.projectFiles.containers.importFail.InitializeAnEmptyDatabase',
            defaultMessage: '初始化空库',
          })}
        </Button>
      ) : null,
      isAdmin ? (
        <Button
          type="normal"
          warning
          onClick={() => {
            this.remove();
            track({
              action: 'delete_repo',
              page: 'Repo-Importing',
              type: 'import by URL',
              control: '',
            });
          }}
          loading={isRemovingProject}
        >
          {intl.get({
            id: 'code-assets.projectFiles.containers.importFail.DeleteACodeLibrary',
            defaultMessage: '删除代码库',
          })}
        </Button>
      ) : null,
    ];

    return (
      <div className="import-failed-page">
        <ListEmpty
          theme="default"
          content={intl.get({
            id: 'code-assets.projectFiles.containers.importFail.ImportFailed',
            defaultMessage: '导入失败',
          })}
          size="large"
          imgType="fail"
          description={this.importFailDescHander()}
          btns={btns}
          className={'code-error-page'}
        />

        {isUrlImportModalShow && (
          <ImportProjectModal
            defaultNamespaceId={defaultNamespaceId}
            closeModal={() => {
              this.closeUrlModal();
            }}
            type="retry"
            projectInfo={projectInfo}
            isModalOpen={isUrlImportModalShow}
            retryCallback={() => {
              // 手动修改import_status使状态立即进入导入中
              setImportStatus('started');
              getProjectInfo();
            }}
          />
        )}
      </div>
    );
  }
}
